import re
import regex
number_dict = {
    '0': '零',
    '1': '一',
    '2': '二',
    '3': '三',
    '4': '四',
    '5': '五',
    '6': '六',
    '7': '七',
    '8': '八',
    '9': '九'
}

class LatexToChinese:
    @staticmethod
    def replace_frac(match):
        a = match.captures(1)
        b = match.captures(2)
        return "{0}分之{1}".format(b[-1], a[-1])

    @staticmethod
    def replace_sqrt(match):
        a = match.group(1)
        return "根号{0}".format(a)

    @staticmethod
    def replace_mathrm(match):
        a = match.group(1)
        return "{0}".format(a)

    @staticmethod
    def replace_pow(match):
        a = match.group(1)
        return "的{0}次方".format(a)

    @staticmethod
    def replace_sub(match):
        a = match.group(1)
        return "{0}".format(a)
    
    @staticmethod
    def replace_abs(match):
        content = match.group(1)
        return f"{content}的绝对值"
    
    @staticmethod 
    def replace_power_(match):
        exponent = match.group(1)
        return f"的{exponent}次方"
        
    @staticmethod
    def escape_colon_in_math_mode(text):
        # 正则表达式匹配 $...$ 之间的内容
        pattern = r'\$(.*?)\$'

        # 替换函数
        def replace_colons(match):
            # 将匹配到的内容中的 : 替换为 比
            inside_dollars = match.group(1)
            return f'${inside_dollars.replace(":", "比")}$'

        # 使用正则表达式的 sub 方法和替换函数
        return regex.sub(pattern, replace_colons, text)

    @staticmethod
    def replace_minus(text):
        # 正则表达式匹配 - 前面是数字或字母的情况
        pattern_digit_or_letter = r'(?<=[0-9A-Za-z\}\)])\-'


        # 替换数字、字母、} 或 ) 后面的 -
        text = regex.sub(pattern_digit_or_letter, '减', text)
        # 将剩余的 - 替换为 负
        text = text.replace('-', '负')

        return text

    @staticmethod
    def replace_sum_expression_1(text):
        # 定义正则表达式模式，匹配\sum_{a}^{b}{c}形式的子字符串
        pattern = r'\\sum_{([\w\+\-=]+)}\^{([\w\+\-=]+)}{([\w\+\-=]+)}'

        # 定义替换函数
        def replace_func(match):
            a, b, c = match.groups()
            print(f"匹配内容：{match.group(0)}")
            return f"从{a}到{b}的{c}的和"
        # 使用正则表达式替换匹配的子字符串
        text = re.sub(pattern, replace_func, text)

        return text

    @staticmethod
    def replace_sum_expression_2(text):
        # 定义正则表达式模式，匹配\sum{a}形式的子字符串
        pattern = r'\\sum\{([\w\+\-=]+)\}'

        # 定义替换函数
        def replace_func(match):
            a = match.group(1)
            return f"{a}的和"

        # 使用正则表达式替换匹配的子字符串
        text = re.sub(pattern, replace_func, text)

        return text

    @staticmethod
    def replace_numbers_with_quotes(text):
        # 使用正则表达式找到所有整数和小数并替换为带引号的形式
        return re.sub(r'(\d+\.\d+|\d+)', r"'\1'", text)

    @staticmethod
    def replace_uppercase_with_quotes(text):
        # 使用正则表达式找到所有大写字母并替换为带引号的形式
        return re.sub(r'([A-Z])', r"'\1'", text)


    # 替换规则集，包括每个规则的正则表达式和处理函数
    replacements_with_brackets = [
        (r"\\sqrt\{([^}]*)\}", replace_sqrt.__get__(object)),
        (r"\\frac{((?:[^{}]|{(?1)})*?)}{((?:[^{}]|{(?1)})*?)}", replace_frac.__get__(object)),
        (r"\\mathrm\{([^}]*)\}", replace_mathrm.__get__(object)),
        (r"\^\{([^}]*)\}", replace_pow.__get__(object)),
        (r"_\{([^}]*)\}", replace_sub.__get__(object)),
        (r'\|([^|]+)\|', replace_abs.__get__(object)),
        (r'\^(\S)', replace_power_.__get__(object))
    ]

    replacements_no_brackets = [
        ('\n', ','),
        ('#', ''),
        ('=', '等于'),
        ('+', '加'),
        ('-', '减'),
        ('<', '小于'),
        ('>', '大于'),
        ('\(', ''),
        ('\)', ''),
        ('\[', ''),
        ('\]', ''),
        (r'\pi', '派'),
        (r'\because', '因为'),
        (r'\therefore', '所以'),
        (r'\times', '乘'),
        (r'\cdot', '点乘'),
        (r'\div', '除以'),
        (r'\triangle', '三角形'),
        (r'\square', '长方形'),
        (r'\angle', '角'),
        (r'^{\circ}', '度'),
        (r'^\circ', '度'),
        (r'\circ', '圆'),
        (r'\odot', '圆'),
        (r'\cong', '全等'),
        (r'\sim', '相似'),
        (r'\pm', '正负'),
        (r'\prep', '垂直'),
        (r'//', '平行'),
        (r'\left(', ''),
        (r'\right)', ''),
        (r'\neq', '不等于'),
        (r'\ne', '不等于'),
        (r'\gt', '大于'),
        (r'\lt', '小于'),
        (r'\leqslant', '小于等于'),
        (r'\leq', '小于等于'),
        (r'\geqslant', '大于等于'),
        (r'\geq', '大于等于'),
        (r'\left\{\begin{array}{l}', ' '),
        (r'\\', '和'),
        (r'\parallel', '平行'),
        (r'\end{array}\right', ' '),
        (r'$', ''),
        (r'*', ''),
        (r' ', ''),
        ("'", '撇'),
        ("\cos", 'cosine'),
        ("\sin", 'sine'),
        ("\\tan", 'tangent'),
        ("\\to", "趋向于"),
        ("\lim", "极限"),
        ("\\vec", "向量"),
        ("\overrightarrow", "向量"),
        (r"\Rightarrow", "推导出"),
        (r"\implies", "推导出"),
        (r"\rightarrow", "推导出"),
        (r"\perp", "垂直"),
        ("①", "一"),
        ("②", "二"),
        ("③", "三"),
        ("④", "四"),
        ("⑤", "五"),
        ("⑥", "六"),
        ("⑦", "七"),
        ("⑧", "八"),
        ("⑨", "九"),
        ("⑩", "十"),
        (r"\begin{cases}", ""),
        (r"\end{cases}", ""),
        (r"\text", ""),
        (r"km/h", "千米每时"),
        (r"m/s", "米每秒"),
        (r"\quad", ""),
        (r"\qquad", ""),

    ]

    @staticmethod
    def replace_text(txt, replacements):
        previous_txt = None

        # 持续进行替换直到文本不再发生变化
        while previous_txt != txt:
            previous_txt = txt
            for pattern, repl_func in replacements:
                txt = regex.sub(pattern, repl_func, txt)

        return txt

    @staticmethod
    def replace_text_no_func(txt, replacements):
        # 对每个替换规则，分别对文本进行处理
        for pattern, repl in replacements:
            txt = txt.replace(pattern, repl)

        return txt

    @staticmethod
    def process_latex(text):
        # 使用定义的replace_frac函数进行替换
        text = text.replace(' ', '')
        text = LatexToChinese.replace_sum_expression_1(text)
        print(text)
        text = LatexToChinese.replace_sum_expression_2(text)
        text = LatexToChinese.replace_minus(text)
        text = LatexToChinese.escape_colon_in_math_mode(text)
        text = LatexToChinese.replace_text_no_func(text, LatexToChinese.replacements_no_brackets)
        # print(text)
        text = LatexToChinese.replace_text(text, LatexToChinese.replacements_with_brackets)
        text = text.replace('{', '').replace('}', '')
        text = LatexToChinese.replace_uppercase_with_quotes(text)
        text = LatexToChinese.replace_numbers_with_quotes(text)
        if text in number_dict:
            text = number_dict[text]
        text = text.replace('\\', '').replace('_', '')
        return text


if __name__ == '__main__':
    txt = r"""故答案是4秒或\(\frac{2}{3}\)秒。
"""

    # 使用定义的replace_frac函数进行替换
    txt = LatexToChinese.process_latex(txt)
    print(txt)
